﻿package cn.poco.pepsi.activity.search;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.poco.pepsi.R;
import cn.poco.pepsi.Service_impl.ISearch;
import cn.poco.pepsi.Service_impl.impl.SearchImpl;
import cn.poco.pepsi.activity.BaseActivity;
import cn.poco.pepsi.adapter.TabSearchAdapter;
import cn.poco.pepsi.bean.Circle;
import cn.poco.pepsi.constants.Constants;
import cn.poco.pepsi.testActivity.TabTest;

public class TabSearchActivity extends BaseActivity {

	private final static String TAG = "TabSearchActivity";
	private final static int GET_CIRCLE_SUCCESS = 1;

	private String cityCode;
	private ListView listview;
	
	/** 保存获取的热门商区信息 **/
	List<Circle> circles;
	
	
	private Handler hThread = null;
	private LinearLayout progressbar;
	private LayoutInflater myinflater;

	// TITLE
	private TextView title;

	// 错误处理机制
	private LinearLayout error;

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_tab_search);
		
		//获得各UI组件
		listview = (ListView) findViewById(R.id.listview);
		listview.setCacheColorHint(0);
		
		//获得两布局
		progressbar = (LinearLayout) findViewById(R.id.progressbar);
		error = (LinearLayout) findViewById(R.id.error);
		
		
		
		// 错误重试按钮，重新加载数据
		Button errorBtn = (Button) findViewById(R.id.tautology);
		errorBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				progressbar.setVisibility(View.VISIBLE);//可见
				error.setVisibility(View.GONE);//隐藏
				
				//根据城市代码(已知)获取热门商区
				hThread.post(new GetHotcircleByCityCode());

			}
		});

		
		//网络连接失败，打开手机系统的网络设置（从本程序跳转到设置的无线和网络 ）
		Button setBtn = (Button) findViewById(R.id.setnet);
		setBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
				startActivity(intent);
			}
		});

		
		
		//设置标题，如：美食天堂 POCO.CN [广州]
		title = (TextView) findViewById(R.id.show_title);
		title.setText("美食天堂 POCO.CN [" + getIntent().getExtras().getString(Constants.CITY_NAME) + "]");
		
		
		myinflater = LayoutInflater.from(this);

		
		//城市地区列表事件处理
		listview.setOnItemClickListener(new OnItemClickListener() {
			
            @Override
                                                                    //position为在列表中的位置
			public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
            	//circles为保存获取的热门商区信息的集合
            	System.out.println("listview 点中-------------->");
            	
            	//更多
				if (circles.get(position - 1).getKey() == "000000") {
					System.out.println("更多-------------->");
					Intent intent = new Intent(TabSearchActivity.this, TabTest.class);
					intent.putExtra(Constants.CITY_CODE, cityCode);
					startActivity(intent);

				//热门优惠
				} else if (circles.get(position - 1).getKey() == "000001") {
					Intent intent = new Intent(TabSearchActivity.this, TabTest.class);
					Bundle bundle = new Bundle();
					bundle.putInt(Constants.DISCOUNT_TYPE, 1);
					bundle.putString(Constants.CITY_CODE, cityCode);
					bundle.putString(Constants.ACTIVITY_TOP_TITLE, "热门优惠");
					intent.putExtras(bundle);
					startActivity(intent);

				//排行榜
				} else if (circles.get(position - 1).getKey() == "000002") {
					Intent rank = new Intent(TabSearchActivity.this, TabTest.class);
					rank.putExtra(Constants.CITY_CODE, cityCode);
					startActivity(rank);
					
					
				//今日网友推荐
				} else if (circles.get(position - 1).getKey() == "000003") {
					// TabActivity.tabs.setCurrentTabByTag("今日网友推荐");
					Intent diary = new Intent(TabSearchActivity.this, TabTest.class);
					diary.putExtra(Constants.CITY_CODE, cityCode);
					startActivity(diary);
					
				//具体地区名称
				} else {
					System.out.println("具体地区名称-------------->");
					Intent intent = new Intent(TabSearchActivity.this, SearchResActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString(Constants.CIRCLE_CODE, String.valueOf(id));
					bundle.putString(Constants.CITY_CODE, cityCode);
					bundle.putString(Constants.ACTIVITY_TOP_TITLE, circles.get(position - 1).getName());
					intent.putExtras(bundle);
					startActivity(intent);
				}
			}
		});

		/** 获取意图传递参数 **/
		cityCode = (String) getIntent().getExtras().get(Constants.CITY_CODE);
		System.out.println("在TabSearchActivity里---------->给变量city赋值"+cityCode);
		HandlerThread handlerThread = new HandlerThread("myhThread");
		handlerThread.start();
		hThread = new Handler(handlerThread.getLooper());
		hThread.post(new GetHotcircleByCityCode());
	}

	// 更新UI操作
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			
			//输入地区  搜索  模块
			case GET_CIRCLE_SUCCESS:
				View convertView = myinflater.inflate(R.layout.main_tab_search_head, null);
				final EditText searchtext = (EditText) convertView.findViewById(R.id.searchtext);
				ImageButton searchbtn = (ImageButton) convertView.findViewById(R.id.searchbutton);
				// 点击查询
				searchbtn.setOnClickListener(new ImageButton.OnClickListener() {
					@Override
					public void onClick(View v) {
						
						//获取输入框里的文本
						String searchContent = searchtext.getText().toString();
						if (!searchContent.trim().equals("")) {
							Intent intent = new Intent(TabSearchActivity.this,TabTest.class);
							Bundle bundle = new Bundle();
							bundle.putString(Constants.SEARCH_CONTENT, searchContent);
							bundle.putString(Constants.CITY_CODE, cityCode);
							intent.putExtras(bundle);
							TabSearchActivity.this.startActivity(intent);
						} else {
							Toast.makeText(TabSearchActivity.this, "请输入搜索关键词", 1).show();
						}
					}
				});
				progressbar.setVisibility(View.GONE);
				listview.addHeaderView(convertView);
				
                //显示列表信息   更新UI
				listview.setAdapter(new TabSearchAdapter(TabSearchActivity.this, circles, cityCode));
				listview.setVisibility(View.VISIBLE);
				break;
				
				
			//连接错误
			case Constants.CONN_ERROR:
				progressbar.setVisibility(View.GONE);
				error.setVisibility(View.VISIBLE);
				break;
			}
		}
	};

	// 根据城市代码获取热门商区
	private final class GetHotcircleByCityCode implements Runnable {
		@Override
		public void run() {
			ISearch srarch = new SearchImpl();
			try {
				System.out.println("cityCode------------>"+cityCode);
				circles = srarch.getHotCircle(Long.decode(cityCode), 1);
				circles.add(new Circle("000000", "更多"));
				if (cityCode.equals("101029001"))
					circles.add(new Circle("000001", "热门优惠"));
				circles.add(new Circle("000002", "排行榜"));
				circles.add(new Circle("000003", "今日网友推荐"));
				Message msg = new Message();
				msg.what = GET_CIRCLE_SUCCESS;
				handler.sendMessage(msg);
			} catch (Exception e) {
				System.out.println("根据城市代码获取热门商区------------>异常");
				Log.e(TAG, e.toString());
				handler.sendEmptyMessage(Constants.CONN_ERROR);
				e.printStackTrace();
			}

		}
	}

}
